package com.goldenKey.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.goldenKey.common.mapper.UserMapper;
import com.goldenKey.common.component.AccountComponent;
import com.goldenKey.common.constant.Constant;
import com.goldenKey.common.exception.AppException;
import com.goldenKey.common.pojo.enumeration.ExceptionEnum;
import com.goldenKey.common.pojo.po.User;
import com.goldenKey.common.utils.JasyptEncryptorUtils;
import com.goldenKey.common.utils.JwtUtils;
import com.goldenKey.common.utils.StringTools;
import com.goldenKey.user.pojo.query.LoginQuery;
import com.goldenKey.user.pojo.query.RegisterQuery;
import com.goldenKey.user.pojo.vo.AccountVo;
import com.goldenKey.user.service.IAccountService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.ReadOnlyProperty;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Author: 吃我一钊
 * @Description: 业务逻辑实现层
 * @Date: 2025/02/02
 */

@Service
public class AccountServiceImpl extends ServiceImpl<UserMapper, User> implements IAccountService {

    @Autowired
    private UserMapper userMapper;
    @Resource
    private AccountComponent accountComponent;

    /**
     * 用户登录
     * @param loginQuery
     * @return
     */
    @Override
    public AccountVo login(LoginQuery loginQuery, HttpServletRequest request) {
        String account = loginQuery.getAccount();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        if (account.matches(Constant.REGEX_EMAIL)) {   // 如果是邮箱格式，则根据邮箱查询
            queryWrapper.eq(User::getEmail, account);
        } else {  // 否则认为是用户名，进行用户名查询
            queryWrapper.eq(User::getUsername, account);
        }

        // 根据账号查询用户
        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            throw new AppException(ExceptionEnum.ACCOUNT_OR_PASSWORD_ERROR);
        }

        // 解密密码并进行验证
        String plainPassword = JasyptEncryptorUtils.decode(user.getPassword());
        if (!loginQuery.getPassword().equals(plainPassword)) {  // 密码错误
            throw new AppException(ExceptionEnum.ACCOUNT_OR_PASSWORD_ERROR);
        }

        // 账号验证通过，生成 token，设置最新登录IP和时间
        user.setLastLoginIp(accountComponent.getClientIp(request));
        user.setLastLoginTime(new Date());
        userMapper.updateById(user);

        String token = JwtUtils.createToken(user.getUserId(), user.getUsername());

        // 构造返回的 AccountVo
        AccountVo accountVo = new AccountVo();
        BeanUtils.copyProperties(user, accountVo);
        accountVo.setUserToken(token);  // 将生成的 token 设置到返回的 VO 中

        return accountVo;
    }

    /**
     * 用户注册
     * @param registerQuery
     * @return
     */
    @Override
    public void register(RegisterQuery registerQuery) {
        // 根据时间戳+随机数生成用户ID
        String userId = StringTools.generateId(6, 6);
        // 密码加密
        String encryptedPassword = JasyptEncryptorUtils.encode(registerQuery.getPassword());

        User user = User.builder()
                .userId(userId)
                .email(registerQuery.getEmail())
                .username(registerQuery.getUsername())
                .password(encryptedPassword)
                .build();

        userMapper.insert(user);
    }

    /**
     * 判断用户表某个字段是否存在该值
     * @param field
     * @param value
     * @return
     */
    @Override
    public Boolean checkIsExist(String field, String value) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(field, value);

        Long count = userMapper.selectCount(queryWrapper);
        return (count > 0) ? true : false;
    }


}